package com.kun.generator.server;

import com.kun.generator.util.FreemarkerUtil;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: ServiceGenerator
 * @Description: 生成Service的代码生成器
 * @author: kunkun
 * @date: 2025/7/27 22:15
 */
public class ServiceGenerator {
    static String servicePath = "[module]/src/main/java/com/kun/service/";
    static String pomPath = "generator\\pom.xml";
    static {
        new File(servicePath).mkdirs();
    }

    public static void main(String[] args) throws Exception {
        //1. 读取TrainProject/pom.xml中代码生成器的xml配置文件路径
        String generatorPath = getGeneratorPath();
        //2. 读取xml配置文件中的信息
        Document document = new SAXReader().read("generator/" + generatorPath);
        Node table = document.selectSingleNode("//table");
        System.out.println(table);
        Node tableName = table.selectSingleNode("@tableName");
        Node domainObjectName = table.selectSingleNode("@domainObjectName");
        System.out.println(tableName.getText()+"---"+domainObjectName.getText());
        //3. 处理servicePath
        String Domain = domainObjectName.getText();
        String domain = Domain.substring(0,1).toLowerCase()+Domain.substring(1);
        String do_main = tableName.getText().replace("_","-");//表名使用-分割
        //generatorPath：src/main/resources/generator-config-member.xml
        String module = generatorPath.replace("src/main/resources/generator-config-","").replace(".xml","");
        module = module.substring(0,1).toUpperCase()+module.substring(1);
        servicePath = servicePath.replace("[module]",module);
        //3. 获取模板，填充模板
        FreemarkerUtil.initConfig("service.ftl");
        HashMap<String, Object> param = new HashMap<>();
        param.put("domain",domain);
        param.put("Domain",Domain);
        param.put("do_main",do_main);
        FreemarkerUtil.generator(servicePath+Domain+"Service.java",param);

    }

    //返回生成器配置文件xml的地址
    private static String getGeneratorPath() throws Exception {
        SAXReader saxReader = new SAXReader();
        Map<String, String> map = new HashMap<>();
        map.put("pom","http://maven.apache.org/POM/4.0.0");
        saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
        Document document = saxReader.read(pomPath);
        Node node = document.selectSingleNode("//pom:configurationFile");
        return node.getText();
    }
}
